import store from '@/store'
import axios from 'axios'
import { Message } from 'element-ui'
// 创建自定义配置的 axios实例
const request = axios.create({
  // baseURL:基地址
  baseURL: process.env.VUE_APP_BASE_URL,
  // 超时时间
  timeout: 20000
})

// 请求拦截器
request.interceptors.request.use(
  config => {
    if (!config.headers.Authorization && store.state.user.token) {
      config.headers.Authorization = `Bearer ${store.state.user.token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
request.interceptors.response.use(
  response => {
    // 处理200请求
    const { message, success } = response.data
    if (success) {
      return response.data
    } else {
      Message.error(message)
      return Promise.reject(message)
    }
  },
  error => {
    return Promise.reject(error)
  }
)

export default request
